package com.foodlocker.machine;



import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;

import com.foodlocker.http.PollingService;
import com.foodlocker.http.PollingUtils;
import com.foodlocker.maintenance.ConfigAct;
import com.foodlocker.maintenance.MaintenancerLoginAct;
import com.foodlocker.sqlite.OrderDao;
import com.foodlocker.bean.Courier;
import com.foodlocker.bean.Machine;
import com.foodlocker.bean.Order;
import com.foodlocker.common.CommonFunction;
import com.foodlocker.common.Constant;
import com.foodlocker.common.UniversalHttpPost;
import com.foodlocker.common.UniversalKeyboard;
import com.foodlocker.courier.AbandomAct;
import com.foodlocker.courier.CourierLoginAct;
import com.foodlocker.courier.DepositAct;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
	

	Context ctx ;
	Activity act;
	EditText pass1,pass2,pass3,pass4,pass5,pass6;
	TextView et_hint;
	TextWatcher tw;
    Button loginButton;
	Button btn_reopen_take,btn_confirm_take,testButton1,testButton2;
	Handler mMainHandler;
	Box mBox;
    OrderDao orderDao;
  //  OnTouchListener passListener;
  //  OnTouchListener keyBordListener;
    Timer noTouchTimer;
  //  KeyboardUtil keyBordUtil;
    JSONObject c_orderJO=null;
    static String SUCCESS="success";
    public static  String StaffLoginCode="";
    String AFFAIR_TAKE_ORDER="orderTaked";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		orderDao= new OrderDao(this);
	
		 //设置无标题         	requestWindowFeature(Window.FEATURE_NO_TITLE);
		  PollingUtils.startPollingService(this, 60, PollingService.class, PollingService.ACTION);
		  define_TouchListener();
		definep_password_watcher();
		init_et_password();
		define_mMainHandler();
	
		mBox= new Box(mMainHandler);
		   ctx = this;
		 act = this;
	    new KeyboardUtil(act, ctx,  pass1,pass2,pass3,pass4,pass5,pass6).showKeyboard();
	    MyOnclickListener myOnclickListener= new MyOnclickListener();
	    btn_reopen_take=(Button)findViewById(R.id.btn_reopen_take);
	    btn_confirm_take=(Button)findViewById(R.id.btn_confirm_take);
		testButton1=(Button)findViewById(R.id.testbutton1);
		testButton1.setOnClickListener(myOnclickListener);
		testButton2=(Button)findViewById(R.id.testbutton2);
		testButton2.setOnClickListener(myOnclickListener);
		btn_reopen_take.setOnClickListener(myOnclickListener);
	    btn_reopen_take.setVisibility(View.INVISIBLE);
		btn_confirm_take.setOnClickListener(myOnclickListener);
	    btn_confirm_take.setVisibility(View.INVISIBLE);
		et_hint=(TextView) findViewById(R.id.et_hint);
		
		loginButton=(Button) findViewById(R.id.loginbutton);
	
		 noTouchTimer= new Timer();
		 noTouchTimer.schedule(new NoTouchTask(), 10*1000);
	}// end of onCreat()
	
	private class MyOnclickListener implements View.OnClickListener{

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if(v==testButton1){
				new OrderDao(MainActivity.this).queryAll();
			                   }	
		
			if(v==btn_reopen_take){
				if(c_orderJO!=null) {
					String boxesIn=c_orderJO.getString(Order.BOXESIN);
			        List<Integer> boxes= new ArrayList<Integer>();
					 for(int i=0;i<boxesIn.length()/3;i++){
						 int boxID=Integer.parseInt(boxesIn.substring(i*3,(i+1)*3));		
						boxes.add(boxID);	
					 }				
					 Message msg = new Message();              
	                 msg.what=1;
	                 msg.obj=boxes;
	                 Box.childHander.sendMessage(msg); }
			}
			
			if(v==btn_confirm_take){
				orderDao.updateOrderState(c_orderJO.getLong(Order.ID), 31); //暂存
				String[] params= new String[3];
		         params[0]=Constant.BaseUrl+Constant.MachineUrl;
		         params[1]=AFFAIR_TAKE_ORDER; //PostCod
		         JSONObject jsonData=new JSONObject();
		         JSONObject simpleMachineJO= new JSONObject();
	             simpleMachineJO.put(Machine.ID, Constant.machineJO.getInt(Machine.ID));
	             simpleMachineJO.put(Machine.SECRET, Constant.machineJO.getString(Machine.SECRET));
	            jsonData.put("machine", simpleMachineJO);  
		         JSONArray orders= new JSONArray();
		         orders.add(c_orderJO);
		         jsonData.put("orders",orders);
		         params[2]=jsonData.toString();		       
		         new HttpPostTask().execute(params);
				
				clearDisplay();			
			}
			
		}
	}
	
	private void init_et_password(){
		
		pass1 = (EditText) findViewById(R.id.et_pass1);
		 pass2 = (EditText) findViewById(R.id.et_pass2);
		 pass3 = (EditText) findViewById(R.id.et_pass3);
		 pass4 = (EditText) findViewById(R.id.et_pass4);
		 pass5 = (EditText) findViewById(R.id.et_pass5);
		 pass6 = (EditText) findViewById(R.id.et_pass6);
		 pass1.addTextChangedListener(tw);
		 pass2.addTextChangedListener(tw);
		 pass3.addTextChangedListener(tw);
		 pass4.addTextChangedListener(tw);
		 pass5.addTextChangedListener(tw);
		 pass6.addTextChangedListener(tw);	
		   pass1.setInputType(0);
		   pass2.setInputType(0);
		   pass3.setInputType(0);
		   pass4.setInputType(0);
		   pass5.setInputType(0);
		   pass6.setInputType(0);
	}
	private void definep_password_watcher(){
		
		 tw = new TextWatcher() {
	            // @Override
	            public void beforeTextChanged(CharSequence s, int start, int count,
	                    int after) {
	 
	            }
	 
	            // @Override
	            public void onTextChanged(CharSequence s, int start, int before,
	                    int count) {
	                //Log.w("Log", "----" + s);
	 
	            }
	 
	         
				@Override
				public void afterTextChanged(Editable s) {
					// TODO Auto-generated method stub
					String otakesecret;
					  if (s.toString().length() == 1) {
		                    if (pass1.isFocused()) {
		                        pass1.clearFocus();
		                        pass2.requestFocus();
		                    } else if (pass2.isFocused()) {
		                        pass2.clearFocus();
		                        pass3.requestFocus();
		                    } else if (pass3.isFocused()) {
		                        pass3.clearFocus();
		                        pass4.requestFocus();
		                    } else if (pass4.isFocused()) {
		                        pass4.clearFocus();
		                        pass5.requestFocus();
					        } else if (pass5.isFocused()) {
	                            pass5.clearFocus();
	                            pass6.requestFocus();
				            } else if (pass6.isFocused()) {
				            	
                                 otakesecret=pass1.getText().toString()+pass2.getText().toString()+pass3.getText().toString()+
                                		 pass4.getText().toString()+pass5.getText().toString()+pass6.getText().toString();
                                 otakesecret=otakesecret.trim();
                                pass6.clearFocus();
                                clearDisplay();
             					System.out.println("StaffLoginCode.isEmpty()="+StaffLoginCode.isEmpty()+"StaffLoginCode="+StaffLoginCode+" otakesecret.equals(Constant.MaintenancerLoginCode)="+otakesecret.equals(Constant.MaintenancerLoginCode)+" otakesecret.equals(Constant.CourierLoginCode)="+otakesecret.equals(Constant.CourierLoginCode));
                               if( otakesecret.equals(Constant.MaintenancerLoginCode)||otakesecret.equals(Constant.CourierLoginCode)){ //约定送货员登陆密码
                            	   if(StaffLoginCode.isEmpty()){
                            		   StaffLoginCode=otakesecret;
                            	   }else{
                            		   if(StaffLoginCode.equals(otakesecret)&&Constant.CourierLoginCode.equals(otakesecret) ){
                            			   StaffLoginCode="";
                            			   Intent intent= new Intent(MainActivity.this, CourierLoginAct.class);       	
                            			   startActivity(intent);	   
                            		   }
                            		   if(StaffLoginCode.equals(otakesecret)&&Constant.MaintenancerLoginCode.equals(otakesecret) ){
                            			   StaffLoginCode="";
                            			   Intent intent= new Intent(MainActivity.this, MaintenancerLoginAct.class); 			 
                            			   startActivity(intent);
                            		   }		   
                            	   }
                               }else{
                            	   StaffLoginCode=""; 
                               }
                                 et_hint.setText("欢迎使用厚豆自提柜\n 您输入的密码是："+otakesecret+"\n");
                                 c_orderJO =orderDao.queryByTakeSecret(otakesecret);	
                                 
                				 if(!c_orderJO.getBoolean(SUCCESS)){ 
                					 System.out.println("THE RESULT OF QUERY BY ORDERSECRET is EMPTY");
                					 et_hint.setText(et_hint.getText().toString()+"没有该订单，如有疑问请联系卖家"+"\n");}
                				 else {
                					 int state= c_orderJO.getInt(Order.STATE);	
                					 et_hint.setText(et_hint.getText().toString()+"订单号："+c_orderJO.getLong(Order.ID)+" \n ");
              					     String noteStr="放在";
                					if(state==21){
                						String boxesIn=c_orderJO.getString(Order.BOXESIN);
                				        List<Integer> boxes= new ArrayList<Integer>();
                						 for(int i=0;i<boxesIn.length()/3;i++){
                							 int boxID=Integer.parseInt(boxesIn.substring(i*3,(i+1)*3));
                							 noteStr+=" "+boxID+"号";
                							boxes.add(boxID);	
                						 }
                						 noteStr+="箱格中 \n";
                						 et_hint.setText(et_hint.getText().toString()+noteStr);
                						 
                						 Message msg = new Message();              
                		                 msg.what=1;
                		                 msg.obj=boxes;
                		                 Box.childHander.sendMessage(msg);
                	                     btn_confirm_take.setVisibility(View.VISIBLE);
                	                     btn_reopen_take.setVisibility(View.VISIBLE);   
                	                     
                					       }
                					
                					if(state==12||state==20){
                						 et_hint.setText(et_hint.getText().toString()+"你的订单还未送达，如有疑问请联系你的卖家"+"\n");
                						                          }
                					if(state==22||state==31){
               						 et_hint.setText(et_hint.getText().toString()+"你的订单已被取走，如有疑问请联系你的卖家"+"\n");
               						                          }
                					if(state==23){
                  						 et_hint.setText(et_hint.getText().toString()+"对不起，由于你一直不来取订单，订单已被卖家取回"+"\n");
                  						                          }
                					if(state==24){
                  						 et_hint.setText(et_hint.getText().toString()+"对不起，由于你一直不来取订单，订单已被丢弃 ，如有疑问请联系卖家"+"\n");
                  						                          }          	          
                                       }// end of else
             		            }
             		        		 
					 
		 } //end of if(s.toString().lenth==1)
				
				} //afterTextChanged(Editable s)
	        };  //end of textwatcher

	
		
		 }  //definep_password_watcher()

	private void define_mMainHandler(){
		
		mMainHandler= new Handler(){
			//   private static final String MAIN_TAG = "MainThread";
	        @Override
	        public void handleMessage(Message msg) {
	            Log.i("MainThread", "Got an incoming message from the child thread -what is: "+msg.what+"obj is:"
	                    + (String) msg.obj);

	            // 接收子线程的消息
	         //   info.setText((String) msg.obj + String.valueOf(nClick));
	        if(msg.what==2) {
	             et_hint.setText((String) msg.obj); }
	        
	        if(msg.what==5){
	        	clearDisplay();
	        
	        }
	        }
	    };
	}
    private void clearDisplay(){
    	c_orderJO=null;
        btn_reopen_take.setVisibility(View.INVISIBLE);
        btn_confirm_take.setVisibility(View.INVISIBLE);
        et_hint.setText("");
        clearPasswordInput();
        pass1.requestFocus();  	
    }
	private void clearPasswordInput(){
		     pass1.setText("");
			pass2.setText("");
			pass3.setText("");
			pass4.setText("");
			pass5.setText("");
			pass6.setText("");
		
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
    
	
	private void define_TouchListener(){
				 
		/* passListener = new  OnTouchListener(){		   
			  @Override  
		      public boolean onTouch(View v, MotionEvent event) {  
				  keyBordUtil= new KeyboardUtil(act, ctx, pass1,pass2,pass3,pass4,pass5,pass6);
				  keyBordUtil.showKeyboard();	
		              return false;  }	 };	    */          		              
	} 
	
     class NoTouchTask extends TimerTask{

		@Override
		public void run() {
			// TODO Auto-generated method stub			                     	             	
			 // 定义一个消息传过去  子线程无法改动UI线程里的空间，所以用消息去更改
            Message msg = new Message(); 
            msg.what = 5; 
            mMainHandler.sendMessage(msg); 
		}
    	 
     }
	@Override
	public void onUserInteraction() {
		// TODO Auto-generated method stub
		super.onUserInteraction();
		noTouchTimer.cancel();
		noTouchTimer=new Timer();
		noTouchTimer.schedule( new NoTouchTask(), 10*1000);
	}
	
	private  class HttpPostTask extends android.os.AsyncTask<String,String,Map<String,Object>>{

		

		@Override
		protected Map<String,Object> doInBackground(String... params) {
			// TODO Auto-generated method stub
			 Map<String,Object> map = new HashMap<String ,Object>();		
		  map =	UniversalHttpPost.doPost(params);	             
			return map;
		}
		
		@Override
		protected void onPostExecute(Map<String,Object> map) {
				
			 System.out.println("-----------onPostExecute()--------------");
		
			 String PostResult=(String) map.get("PostResult");		 
			 boolean networkstate=(Boolean) map.get("PostState");
			 if(!networkstate){return;}
			//	Toast.makeText(DepositAct.this, "服务器返回数据为"+PostResult, Toast.LENGTH_SHORT).show();
			    JSONObject json = null;
			    int resultCode=-1;
				String resultInfo="";
				String affair="";				
				JSONObject jo;
				try{
			     json= JSONObject.fromObject(PostResult);
			     resultCode=json.getInt("resultCode");
			     resultInfo=json.getString("resultInfo");	
			     affair =json.getString("affair");	
			     jo= json.getJSONObject("jo");
				}catch(JSONException e){return;}
				if(affair.equals(AFFAIR_TAKE_ORDER)){
					if(resultCode==2){
						JSONArray orderTaked= jo.getJSONArray("orders");
						new OrderDao(MainActivity.this).updateOrdersState(orderTaked, 22);
						   return;	 
					}					
				}		
		} //onPostExecute
	} //AsyncTask
 }
